import axios from 'axios'
import router from '@/router'
import { getToken, removeToken } from './auth'
const service = axios.create({
  baseURL: import.meta.env.VITE_BASE_API,
  timeout: 1000 * 5 // 请求超时时间
})

// request拦截器

service.interceptors.request.use(
  (config) => {
    config.headers['Authorization'] = getToken()
    // config.headers['Authorization'] =
    //   'Bearer ' +
    //   'eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6ImE0YTg5OTlkLTc3YWYtNDczNC04MDI1LWU3NDVhZGFlZTAyZCJ9.q-8EpoimQKN2wo2M87s3pWNjNG6HB29rk8NVFasMlwCsIm-wrKxkcNXyD93k3cWHIP1WxKCv57XhDyoNeJO_xQ'
    return config
  },
  (error) => {
    // console.error('error: ', error) // for debug
    Promise.reject(error)
  }
)

// respone拦截器
service.interceptors.response.use(
  (response) => {
    const { code, msg } = response.data
    if (code === 200) {
      return response.data
    } else {
      // 业务错误
      console.log(code)
      if (code === 401) {
        removeToken()
        router.push('/login')
      } else {
        showFailToast(msg)
      }
      return Promise.reject(new Error(msg))
    }
  },
  (error) => {
    return Promise.reject(error)
  }
)

export default service
